package jvlite.mvc;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.Callable;

import jvlite.core.JLiteAPP;
import jvlite.core.JLiteContext;
import jvlite.ioc.BeanFactory;
import jvlite.mvc.annotaion.Action;
import jvlite.mvc.annotaion.ActionMetod;
import jvlite.mvc.annotaion.Boot;
import jvlite.util.LogUtil;

public class ActionLoader implements Callable<Boolean> {

	private static void organizeActions() {
		Map<String, String> allActionMap = JLiteContext.allActionMap;
		for (Class<?> cc : JLiteContext.clazzSet) {
			if (cc.isAnnotationPresent(Action.class)) {
				// obtain the content of @action
				Action action = cc.getAnnotation(Action.class);
				Method[] methods = cc.getDeclaredMethods();
				for (Method method : methods) {
					// judge whether there is @ActionMetod or not
					if (method.isAnnotationPresent(ActionMetod.class)) {
						// obtain the content of @ActionMetod
						ActionMetod actionMetod = method
								.getAnnotation(ActionMetod.class);
						// assemble them to a map that contain the URL mapping
						// the
						// @ActionMetod and @ActionMetod
						allActionMap.put(
								action.value() + "/" + actionMetod.value(),
								cc.getName() + "." + method.getName());
					}
				}
				// initialize config
			} else if (cc.isAnnotationPresent(Boot.class)) {
				Object app = BeanFactory.getBeanMap().get(cc.getName());
				if (app != null) {
					((JLiteAPP) app).doConfig();
				} else {
					LogUtil.info("No custom config found");
				}
			}
		}
	}

	@Override
	public Boolean call() throws Exception {
		organizeActions();
		return true;
	}

}